package api

import (
	"encoding/json"
	"fmt"
	"github.com/go-playground/validator/v10"
	"todolist/conf"
	"todolist/pkg/e"
	"todolist/serializer"
)

func ErrorResponse(err error) serializer.Response {
	if ve, ok := err.(validator.ValidationErrors); ok {
		for _, err := range ve {
			field := conf.T(fmt.Sprintf("Field.%s", err.Field))
			tag := conf.T(fmt.Sprintf("Tag.Valid.%s", err.Tag))
			return serializer.Response{
				Status: e.InvalidParams,
				Msg:    fmt.Sprintf("%s%s", field, tag),
				Error:  err.Error(),
			}
		}
	}
	if _, ok := err.(*json.UnmarshalTypeError); ok {
		return serializer.Response{
			Status: e.ErrorDatabase,
			Msg:    "JSON matching Error",
			Error:  err.Error(),
		}
	}
	return serializer.Response{
		Status: e.InvalidParams,
		Msg:    "Invalid Parameters",
		Error:  err.Error(),
	}
}
